<template>
	<view class="publishShop">
		<u-navbar title="成为销售商" safeAreaInsetTop fixed placeholder>
			<view class="coreshop-navbar-left-slot" slot="left">
				<u-icon name="arrow-left" size="19" @click="goNavigateBack"></u-icon>
				<u-line direction="column" :hairline="false" length="16" margin="0 8px"></u-line>
				<u-icon name="home" size="22" @click="goHome"></u-icon>
			</view>
			<view slot="right">
			</view>
		</u-navbar>

		<form class="form" @submit="formSubmit">
			<view class="uni-form-item uni-column">
				<view class="title">名称
					<view class="valate-icon">*</view>
				</view>
				<input class="uni-input" name="name" placeholder="请输入名称" />
			</view>
			<view class="uni-form-item uni-column">
				<view class="title">手机号
					<view class="valate-icon">*</view>
				</view>
				<input class="uni-input" name="mobile" placeholder="请输入手机号" />
			</view>
			<view class="uni-form-item uni-column">
				<view class="title">公司名称
					<view class="valate-icon">*</view>
				</view>
				<input class="uni-input" name="companyName" placeholder="请输入公司名称" />
			</view>
			<view class="uni-form-item uni-column">
				<view class="title">公司地址
					<view class="valate-icon">*</view>
				</view>
				<view class="loction" @click="handleSelect">{{ pickerValue? pickerValue: '请选择公司所在地'}}</view>
				<image class="arrow-icon" src="/static/images/arrow-right-bold.png" @click="handleSelect"></image>
				<!-- 省市区的-->
				<coreshop-select v-model="show" mode="mutil-column-auto" :list="pickerList" :default-value="pickerIndex"
					@confirm="onConfirm"></coreshop-select>
				<textarea style="width: 210rpx;text-align: right;" class="uni-input" name="companyAddress"
					placeholder="请输入公司详细地址" />
			</view>
			<view class="uni-form-item uni-column" style="border: none;">
				<view class="title">营业执照</view>
			</view>
			<view class="upload-list" style="border-bottom: 2rpx solid #E1E1E1;">
				<view v-if="!imageValueCompany.length" class="addUpload-card" @click="handleUpload('business')">
					<div class="center">
						<image class="add-icon" src="/static/images/add-icon.png"></image>
						<text>营业执照</text>
					</div>
				</view>
				<view class="upload-card" v-else>
					<div class="close">
						<image class="close-icon" src="/static/images/X.png" alt="" @click="handleClose('business')" />
					</div>
					<image class="img" v-for="item in images" :src="item" alt="" srcset="" />
				</view>
			</view>
			<view class="uni-form-item uni-column" style="border: none;">
				<view class="title">身份证</view>
			</view>
			<view class="upload-list" style="border-bottom: 2rpx solid #E1E1E1;">

				<view v-if="!identityCard.front.length" class="addUpload-card" @click="handleUpload('front')">
					<div class="center">
						<image class="add-icon" src="/static/images/sfzzm.png"></image>
						<text>身份证正面</text>
					</div>
				</view>
				<view class="upload-card" v-else>
					<div class="close">
						<image class="close-icon" src="/static/images/X.png" alt="" @click="handleClose('front')" />
					</div>
					<image class="img" v-for="item in identityCard.front" :src="item" alt="" srcset="" />
				</view>

				<view v-if="!identityCard.reverse.length" class="addUpload-card" @click="handleUpload('reverse')">
					<div class="center">
						<image class="add-icon" src="/static/images/sfzfm.png"></image>
						<text>身份证反面</text>
					</div>
				</view>
				<view class="upload-card" v-else>
					<div class="close">
						<image class="close-icon" src="/static/images/X.png" alt="" @click="handleClose('reverse')" />
					</div>
					<image class="img" v-for="item in identityCard.reverse" :src="item" alt="" srcset="" />
				</view>
			</view>
			<view class="uni-form-item uni-column">
				<checkbox-group name="agreement">
					<label>
						<checkbox value="on" /><text>是否同意协议</text>
					</label>
				</checkbox-group>
			</view>
			<button class="submit-btn" form-type="submit">提交</button>
		</form>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				upLoadAction: this.$globalConstVars.apiBaseUrl + '/Api/Common/UploadImages', // 文件上传的api的url
				imageValueCompany: [],
				identityCard: {
					front: [],
					reverse: []
				},
				supplierId: '',
				rules: [{
						field: 'agreement',
						msg: '请勾选协议'
					},
					{
						field: 'companyAddress',
						msg: '公司详细地址不能为空'
					},
					{
						field: 'location',
						msg: '公司所在地不能为空'
					},
					{
						field: 'companyName',
						msg: '公司名称不能为空'
					},
					{
						field: 'mobile',
						msg: ["手机号不能为空", "手机号格式不正确"]
					},
					{
						field: 'name',
						msg: '姓名不能为空'
					}
				],
				show: false,
				pickerList: this.$db.get("areaList"),
				province: this.$db.get("areaList"),
				pickerIndex: [17, 11, 1], // picker索引值
				region: [],
				pickerValue: '',
				provinceKey: 17, //省份id
				cityKey: 11, //市id
				areaKey: 1, //区域id
				areaId: this.$store.state.config.reshipAreaId || 0,
				page: 1,
				limit: 18,
				searchIpt: '',
			}
		},
		onLoad(option) {
			const {
				id
			} = option
			this.supplierId = id
			const chooseLocation = requirePlugin('chooseLocation');
			const location = chooseLocation.getLocation();
			if (location != null) {
				this.form.latitude = location.latitude;
				this.form.longitude = location.longitude;
				this.region = [location.province, location.district, location.city];
				this.form.street = location.name;
			}
			this.getMyLocation()
			this.init()
			console.log(id);
		},
		onUnload() { // 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
			// #ifdef MP-WEIXIN 
			chooseLocation.setLocation(null);
			// #endif
		},
		methods: {
			init() {
				this.getFullPath(this.areaId, this.province);
				this.pickerIndex = [this.provinceKey, this.cityKey, this.areaKey];
			},
			formSubmit(data) { // 提交
				const dValue = data.detail.value
				const validates = []
				const rules = this.rules
				console.log(dValue);
				// 规则的遍历
				rules.forEach((item, idx) => {
					console.log(dValue?.[item.field]);
					if (dValue[item.field]) {
						if (item.field === 'mobile') {
							if (/^[1][3-9][0-9]{9}$/.test(dValue[item.field])) {
								validates.push(true)
							} else {
								validates.push(false)
								uni.showToast({
									title: rules[idx].msg[1],
									duration: 1000
								})
								return
							}
						} else {
							validates.push(true)
						}
					} else {
						if (item.field === 'location') {
							if (this.pickerValue) {
								validates.push(true)
							} else {
								validates.push(false)
								uni.showToast({
									title: Array.isArray(rules[idx].msg) ? rules[idx].msg[0] : rules[idx]
										.msg,
									duration: 1000
								})
								return
							}
						} else {
							validates.push(false)
							uni.showToast({
								title: Array.isArray(rules[idx].msg) ? rules[idx].msg[0] : rules[idx].msg,
								duration: 1000
							})
							return
						}
					}

					if (item.field === 'agreement') {
						if (dValue[item.field].length > 0) {
							validates.push(true)
						} else {
							validates.push(false)
							uni.showToast({
								title: rules[idx],
								duration: 1000
							})
							return
						}
					}
				})
				console.log(validates);
				// 规则的判断
				if (validates.every(item => item == true)) {
					const params = {
						...dValue,
						supplierId: this.supplierId,
						agreement: dValue.agreement.join(''),
						companyAddress: this.pickerValue + dValue.companyAddress,
						imageValueCompany: this.imageValueCompany.join('')
					}
					console.log("params::::::", params);
					this.$u.api.getApplyDealer(params).then(res => {
						console.log(res);
					})
				}
			},
			handleUpload(type) { // 文件上传
				const that = this
				uni.chooseImage({
					success: function(res) {
						var tempFilePaths = res.tempFilePaths;
						uni.uploadFile({
							url: that.upLoadAction, //非真实的接口地址
							fileType: 'image',
							filePath: tempFilePaths[0],
							header: {
								'Accept': 'application/json',
								'Content-Type': 'multipart/form-data',
								'Authorization': 'Bearer ' + that.$db.get('userToken')
							},
							name: 'file',
							success: function({
								data
							}) {
								const newData = JSON.parse(data)
								const fileUrl = newData.data.fileUrl
								switch (type) {
									case 'business':
										that.imageValueCompany.push(fileUrl)
										break
									case 'front':
										that.identityCard.front.push(fileUrl)
										break
									case 'reverse':
										that.identityCard.reverse.push(fileUrl)
										break
								}
								console.log(that.imageValueCompany, that.identityCard.front, that
									.identityCard.reverse);
							},
							fail: function(error) {
								uni.showToast({
									title: '文件上传失败',
									duration: 1000
								})
							}
						});
					}
				});
			},
			handleClose(type) { // 删除图片
				switch (type) {
					case 'business':
						this.imageValueCompany = []
						break
					case 'front':
						this.identityCard.front = []
						break
					case 'reverse':
						this.identityCard.reverse = []
						break
				}
			},
			handleSelect() { // 选择所在地
				this.show = true
			},
			getMyLocation() {
				let _this = this;
				// #ifdef MP-WEIXIN
				wx.getFuzzyLocation({
					type: 'wgs84',
					success(res) {
						_this.latitude = res.latitude
						_this.longitude = res.longitude
						console.log('当前位置的经度1：' + res);
					},
					fail: function() {
						_this.$u.toast("获取您的经纬度坐标失败")
					}
				})
				// #endif
				// #ifndef MP-WEIXIN
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						_this.longitude = res.longitude;
						_this.latitude = res.latitude;
						console.log('当前位置的经度2：' + res);
					},
					fail: function() {
						_this.$u.toast("获取您的经纬度坐标失败")
					}
				});
				// #endif
			},
			getFullPath(id, data) { //倒查城市信息
				for (var i = 0; i < data.length; i++) {
					if (id == data[i].value) {
						if (!data[i].children) {
							this.areaKey = i;
							return true;
						} else if (data[i].hasOwnProperty("children")) {
							if (data[i].children[0] && !data[i].children[0].children) {
								this.cityKey = i;
								return true;
							} else {
								this.provinceKey = i;
								return true;
							}
						}
					} else {
						if (data[i].hasOwnProperty("children")) {
							if (data[i].children[0] !== undefined) {
								if (data[i].children[0].hasOwnProperty("children")) {
									this.provinceKey = i;
								} else {
									this.cityKey = i;
								}
							}
							if (typeof data[i].children != 'undefined') {
								var res = this.getFullPath(id, data[i].children);
								if (res) {
									return true;
								}
							}
						}
					}
				}
			},
			onConfirm(e) { //
				console.log(e);
				let provinceName = e[0].label;
				let cityName = e[1].label;
				let countyName = e[2].label;
				this.pickerValue = e[0].label + "/" + e[1].label + "/" + e[2].label
				let data = {
					provinceName: provinceName,
					provinceId: e[0].value,
					cityName: cityName,
					cityId: e[1].value,
					countyName: countyName,
					countyId: e[2].value,
				}
				this.$u.api.getAreaId(data).then(res => {
					if (res.status) {
						this.areaId = res.data;
					} else {
						uni.showModal({
							title: '提示',
							content: '地区选择出现问题，请重新选择地区',
							showCancel: false
						});
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #fff !important;
	}

	.publishShop {
		padding: 14rpx 26rpx;

		.submit-btn {
			position: fixed;
			left: 50%;
			transform: translateX(-50%);
			bottom: 60rpx;
			width: 90vw;
			height: 90rpx;
			line-height: 90rpx;
			border-radius: 36rpx;
			background-color: #D0241C;
			color: #fff;
			font-size: 28rpx;
			z-index: 999;
		}


		.form {
			padding: 20rpx 28rpx;

			.uni-form-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 28rpx 0;
				border-bottom: 2rpx solid #E1E1E1;

				textarea {
					width: 100%;
					height: 90rpx;
				}

				.title {
					position: relative;
				}

				.loction {
					color: #808080;
					font-size: 32rpx;
				}

				.uni-input {
					width: 70%;
					text-align: right;
				}

				.valate-icon {
					position: absolute;
					top: 1rpx;
					right: -20rpx;
					color: #D0241C;
					font-size: 26rpx;
					margin-left: 8rpx;
				}

				.arrow-icon {
					width: 30rpx;
					height: 30rpx;
				}
			}
		}


		.upload-list {
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			padding-bottom: 28rpx;

			.addUpload-card {
				width: 25%;
				height: 180rpx;
				border: 3rpx dashed #E0E0E0;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-right: 20rpx;

				.center {
					display: flex;
					flex-direction: column;
					align-items: center;

					.add-icon {
						width: 80rpx;
						height: 80rpx;
					}

					text {
						margin-top: 12rpx;
						color: #DEDEDE;
						font-size: 30rpx;
					}
				}
			}

			.upload-card {
				position: relative;
				width: 25%;
				margin: 0 14rpx;
				height: 180rpx;
				box-sizing: border-box;
				border: 3rpx dashed #E0E0E0;

				&:hover {
					border-color: #c2c2c7;
				}

				.img {
					width: 100%;
					height: 100%;
				}

				.close {
					position: absolute;
					top: 10rpx;
					right: 10rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					width: 30rpx;
					height: 30rpx;
					background-color: rgba(255, 255, 255, .8);
					border-radius: 50%;

					.close-icon {
						width: 20rpx;
						height: 20rpx;
					}
				}
			}

		}
	}
</style>